package controller

import (
	"log"
	"strconv"
	"strings"

	"github.com/bear/wolf/model"
	"github.com/bear/wolf/request"
	"github.com/bear/wolf/utils"
	"github.com/gin-gonic/gin"
)

//任务类型---多个任务对应一个项目
func DeleteTaskById(c *gin.Context){
	id := c.Query("id")
	if strings.TrimSpace(id) == ""{
		utils.Failed(c,"id不能为空:")
		return
	}
	int_id, _ := strconv.Atoi(id)
	result := model.DeleteByTaskId(int_id)
	if result != nil{
	utils.Failed(c,"删除失败:")
		return
	}
	utils.Success(c,gin.H{
		"id":       id,
	})
}
//获取单个task
func GetTaskOne(c *gin.Context){
	id := c.Query("id")
	if strings.TrimSpace(id) == ""{
		utils.Failed(c,"id不能为空:")
		return
	}
	idUint ,_:=strconv.Atoi(id)
	result := model.GetTaskById(idUint)
	if result.Id == 0 {
		utils.Failed(c,"暂无数据")
		return
	}
	utils.Success(c,result)
}

//新增单个task
func AddTask(c *gin.Context){
	var req request.TaskCreReq
	if err := c.ShouldBindJSON(&req); err !=nil{
		utils.Failed(c,"无效的请求"+ err.Error())
		return
	}
	count := model.GetTaskByname(req.TaskName)
	if count !=0{
		utils.Failed(c,"存在相同任务名称")
		return
	}
	beginAt1, _ := utils.ParseDate(req.BeginAt)
	endAt1 , _ := utils.ParseDate(req.EndAt)

	task := model.Task{
		ProjectId 	: utils.StringToInt(req.ProjectId),
		PId     	: utils.StringToInt(req.PId),
		TaskName    : req.TaskName,
		BeginAt     : beginAt1,
		EndAt       : endAt1,
		TaskType    : utils.StringToInt(req.TaskType),
		PlanTime    : utils.StringToInt(req.PlanTime),
		ActTime    	: utils.StringToInt(req.ActTime),
	}
	result1 := model.CreateTask(&task,req.UserIds)
	if result1 !=nil{
		utils.Failed(c,"task新增失败"+result1.Error())
		return
	}
	utils.Success(c,task)
}

func UpTask(c *gin.Context){
	var req request.TaskUpdReq
	if err := c.ShouldBindJSON(&req); err !=nil{
		utils.Failed(c,"无效的请求"+ err.Error())
		return
	}
	result := model.GetTaskById(req.Id)
	if result.Id ==0{
		utils.Failed(c,"无效的数据")
		return
	}
	beginAt1, _ := utils.ParseDate(req.BeginAt)
	endAt1 , _ := utils.ParseDate(req.EndAt)

	task := model.Task{
		Id: req.Id,
		ProjectId 	: utils.StringToInt(req.ProjectId),
		PId     	: utils.StringToInt(req.PId),
		TaskName    : req.TaskName,
		BeginAt     : beginAt1,
		EndAt       : endAt1,
		TaskType    : utils.StringToInt(req.TaskType),
		PlanTime    : utils.StringToInt(req.PlanTime),
		ActTime    	: utils.StringToInt(req.ActTime),
	}
	resu1 := model.UpdateTaskId(&task,req.UserIds)
	if resu1 !=nil{
		utils.Failed(c,"更新失败"+resu1.Error())
		return
	}
	utils.Success(c,task)
}

func GetTaskList(c *gin.Context){
	projectId := c.Query("projectId")
	taskName := c.Query("taskName")
	taskType := c.Query("taskType")
	log.Printf("=========")
	taskList := model.GetTaskList(projectId,taskName,taskType)
	utils.Success(c,taskList)
}



